<template>
  <div class="station-list">
    <div class="search-box">
      <input 
        v-model="searchKeyword"
        placeholder="搜索充电站名称、地址或品牌..."
        class="search-input"
        aria-label="搜索充电站"
        @input="handleSearch"
      />
      <button 
        v-if="searchKeyword" 
        class="clear-search" 
        @click="clearSearch"
        aria-label="清除搜索"
      >
        ×
      </button>
    </div>
    
    <!-- 位置信息显示 -->
    <div class="location-info" v-if="currentLocation">
      <span class="location-icon">📍</span>
      <span class="location-text">{{ currentLocation.address || `当前位置: ${currentLocation.latitude.toFixed(6)}, ${currentLocation.longitude.toFixed(6)}` }}</span>
      <button class="refresh-location" @click="getCurrentLocation" aria-label="刷新位置">
        🔄
      </button>
    </div>

    <!-- 路线信息 -->
    <div class="route-info" v-if="selectedRoute">
      <div class="route-header">
        <h4>导航路线</h4>
        <button @click="clearRoute" aria-label="关闭路线">×</button>
      </div>
      <div class="route-details">
        <p>距离: {{ selectedRoute.distance }}公里</p>
        <p>预计时间: {{ selectedRoute.duration }}分钟</p>
        <button class="start-navigation" @click="startNavigation">
          🚗 开始导航
        </button>
      </div>
    </div>

    <!-- 虚拟滚动容器 -->
    <RecycleScroller
      v-if="enableVirtualScroll"
      class="stations-container"
      :items="virtualStations"
      :item-size="200"
      key-field="stationId"
      v-slot="{ item: station }"
    >
      <StationListItem
        :station="station"
        :is-selected="store.selectedStation?.stationId === station.stationId"
        @select="handleStationClick"
        @charge="startCharging"
        @show-route="showRoute"
      />
    </RecycleScroller>

    <!-- 传统滚动容器（备用） -->
    <div v-else class="stations-container">
      <div 
        v-for="station in filteredStations" 
        :key="station.stationId"
        class="station-item"
        :class="{ 
          active: store.selectedStation?.stationId === station.stationId,
          charging: isStationCharging(station.stationId)
        }"
        @click="handleStationClick(station)"
        :aria-label="`充电站: ${station.stationName}, ${getStationAccessibilityLabel(station)}`"
        role="button"
        tabindex="0"
        @keydown.enter="handleStationClick(station)"
      >
        <div class="station-header">
          <h3 class="station-name">{{ station.stationName }}</h3>
          <span class="distance">{{ store.formatDistance(station.distance) }}</span>
        </div>
        
        <div class="station-info">
          <p class="address">{{ station.address }}</p>
          <p class="brand">品牌：{{ station.brandName }}</p>
          <p class="hours">营业时间：{{ station.openTime }}</p>
        </div>
        
        <div class="station-status">
          <div class="charger-info">
            <span class="label">快充：</span>
            <span class="count">{{ station.quickAvailableNum }}/{{ station.quickChargeNum }}</span>
          </div>
          <div class="charger-info">
            <span class="label">慢充：</span>
            <span class="count">{{ station.slowAvailableNum }}/{{ station.slowChargeNum }}</span>
          </div>
          <div class="price">¥{{ station.totalCostPrice }}/度</div>
        </div>
        
        <!-- 状态徽章 - 现在更明显 -->
        <div 
          class="status-badge" 
          :class="store.getStationStatus(station)"
          :aria-label="`状态: ${getStatusText(store.getStationStatus(station))}`"
        >
          <span class="status-icon">
            {{ getStatusIcon(store.getStationStatus(station)) }}
          </span>
          {{ getStatusText(store.getStationStatus(station)) }}
        </div>

        <!-- 操作按钮组 -->
        <div class="station-actions">
          <button 
            class="route-btn" 
            @click.stop="showRoute(station)"
            :disabled="!currentLocation"
            aria-label="查看路线"
          >
            🗺️ 路线
          </button>
          <button 
            class="charge-btn" 
            @click.stop="startCharging(station)"
            :disabled="store.getAvailableCount(station) === 0 || isStationCharging(station.stationId)"
            :aria-label="getChargeButtonLabel(station)"
          >
            {{ getChargeButtonText(station) }}
          </button>
        </div>
      </div>
    </div>

    <!-- 充电确认对话框 -->
    <div v-if="showChargingConfirm" class="modal-overlay">
      <div class="charging-modal" role="dialog" aria-labelledby="charging-modal-title">
        <h3 id="charging-modal-title">确认开始充电</h3>
        <div class="charging-info">
          <p><strong>充电站:</strong> {{ selectedChargingStation?.stationName }}</p>
          <p><strong>地址:</strong> {{ selectedChargingStation?.address }}</p>
          <p><strong>价格:</strong> ¥{{ selectedChargingStation?.totalCostPrice }}/度</p>
          <p><strong>可用桩位:</strong> {{ store.getAvailableCount(selectedChargingStation!) }}个</p>
        </div>
        <div class="modal-actions">
          <button class="btn-cancel" @click="cancelCharging" aria-label="取消充电">
            取消
          </button>
          <button class="btn-confirm" @click="confirmCharging" aria-label="确认开始充电">
            开始充电
          </button>
        </div>
      </div>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-overlay">
      <div class="loading-spinner"></div>
      <p>加载中...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
// import { useRouter } from 'vue-router' // 暂时注释掉未安装的依赖
import { useStationsStore } from '@/stores/station'
import type { Station } from '@/types/station'

// 虚拟滚动相关导入
// import { RecycleScroller } from 'vue-virtual-scroller' // 暂时注释掉未安装的依赖
import 'vue-virtual-scroller/dist/vue-virtual-scroller.css'

// const router = useRouter() // 暂时注释掉未安装的依赖
const store = useStationsStore()
const searchKeyword = ref('')
const currentLocation = ref<{latitude: number; longitude: number; address?: string} | null>(null)
const selectedRoute = ref<{distance: string; duration: string; steps: any[]} | null>(null)
const showChargingConfirm = ref(false)
const selectedChargingStation = ref<Station | null>(null)
const loading = ref(false)
const chargingStations = ref<Set<string>>(new Set()) // 正在充电的站点

// 虚拟滚动相关
const enableVirtualScroll = ref(false)
const virtualStations = computed(() => filteredStations.value)

// 搜索功能
const handleSearch = () => {
  // 可以添加防抖优化
  console.log('搜索:', searchKeyword.value)
}

const clearSearch = () => {
  searchKeyword.value = ''
}

// 过滤站点
const filteredStations = computed(() => {
  if (!searchKeyword.value.trim()) {
    return store.stations
  }
  
  const keyword = searchKeyword.value.toLowerCase()
  return store.stations.filter(station => 
    station.stationName.toLowerCase().includes(keyword) ||
    station.address.toLowerCase().includes(keyword) ||
    station.brandName.toLowerCase().includes(keyword)
  )
})

// 状态显示
const getStatusText = (status: string) => {
  const statusMap = {
    free: '空闲',
    busy: '繁忙', 
    maintenance: '维护中'
  }
  return statusMap[status as keyof typeof statusMap] || '未知'
}

const getStatusIcon = (status: string) => {
  const iconMap = {
    free: '✅',
    busy: '🟡',
    maintenance: '🔴'
  }
  return iconMap[status as keyof typeof iconMap] || '❓'
}

// 定位功能
const getCurrentLocation = () => {
  loading.value = true
  if (!navigator.geolocation) {
    alert('您的浏览器不支持地理位置服务')
    loading.value = false
    return
  }

  navigator.geolocation.getCurrentPosition(
    async (position) => {
      const { latitude, longitude } = position.coords
      currentLocation.value = { latitude, longitude }
      
      try {
        // 获取地址信息（这里使用模拟数据，实际应该调用地图API）
        const address = await reverseGeocode(latitude, longitude)
        currentLocation.value.address = address
        store.setUserLocation(latitude, longitude)
      } catch (error) {
        console.error('获取地址失败:', error)
      }
      loading.value = false
    },
    (error) => {
      console.error('获取位置失败:', error)
      alert('无法获取您的位置，请检查位置权限设置')
      loading.value = false
    },
    {
      enableHighAccuracy: true,
      timeout: 10000,
      maximumAge: 60000
    }
  )
}

// 模拟反向地理编码
const reverseGeocode = async (lat: number, lng: number): Promise<string> => {
  // 实际项目中应该调用地图API如高德、百度等
  return new Promise((resolve) => {
    setTimeout(() => {
      resolve(`北京市朝阳区模拟地址 ${lat.toFixed(4)}, ${lng.toFixed(4)}`)
    }, 500)
  })
}

// 路线规划
const showRoute = async (station: Station) => {
  if (!currentLocation.value) {
    alert('请先获取当前位置')
    return
  }

  loading.value = true
  try {
    // 模拟路线规划API调用
    const route = await calculateRoute(
      currentLocation.value.latitude,
      currentLocation.value.longitude,
      station.lat,
      station.lng
    )
    selectedRoute.value = route
    store.setSelectedStation(station)
  } catch (error) {
    console.error('路线规划失败:', error)
    alert('路线规划失败，请稍后重试')
  }
  loading.value = false
}

// 模拟路线计算
const calculateRoute = async (startLat: number, startLng: number, endLat: number, endLng: number) => {
  return new Promise<{distance: string; duration: string; steps: any[]}>((resolve) => {
    setTimeout(() => {
      // 模拟计算距离和时间
      const distance = calculateDistance(startLat, startLng, endLat, endLng)
      const duration = Math.round(distance * 3) // 模拟行驶时间
      resolve({
        distance: distance.toFixed(1),
        duration: duration.toString(),
        steps: [
          { instruction: `从当前位置出发` },
          { instruction: `沿路行驶约${duration}分钟` },
          { instruction: `到达${distance.toFixed(1)}公里外的充电站` }
        ]
      })
    }, 1000)
  })
}

// 计算两点间距离（简化的Haversine公式）
const calculateDistance = (lat1: number, lon1: number, lat2: number, lon2: number): number => {
  const R = 6371 // 地球半径（公里）
  const dLat = (lat2 - lat1) * Math.PI / 180
  const dLon = (lon2 - lon1) * Math.PI / 180
  const a = 
    Math.sin(dLat/2) * Math.sin(dLat/2) +
    Math.cos(lat1 * Math.PI / 180) * Math.cos(lat2 * Math.PI / 180) * 
    Math.sin(dLon/2) * Math.sin(dLon/2)
  const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a))
  return R * c
}

const clearRoute = () => {
  selectedRoute.value = null
}

const startNavigation = () => {
  if (selectedRoute.value) {
    // 实际应该调用地图APP或Web导航
    alert('开始导航到选定的充电站')
  }
}

// 充电功能增强
const startCharging = async (station: Station) => {
  console.log('⚡ 开始充电流程:', station.stationName)
  
  // 检查可用性
  if (store.getAvailableCount(station) === 0) {
    alert('该充电站暂无可用桩位')
    return
  }

  if (isStationCharging(station.stationId)) {
    alert('该充电站正在充电中')
    return
  }

  // 显示确认对话框
  selectedChargingStation.value = station
  showChargingConfirm.value = true
}

const confirmCharging = async () => {
    if (!selectedChargingStation.value) return

    loading.value = true
    try {
      // 模拟开始充电会话
      // const result = await store.startChargingSession(selectedChargingStation.value.stationId)
      // 模拟成功响应
      const result = { success: true }
      
      if (result.success) {
        // 标记为充电中
        chargingStations.value.add(selectedChargingStation.value.stationId)
        
        // 显示成功消息
        alert('开始充电成功！')
        
        // 刷新站点列表 - 使用现有方法
        if (currentLocation.value) {
          // loadStations方法不接受参数
          await store.loadStations()
        } else {
          // 使用loadStations替代refreshStations
          // loadStations方法不接受参数
          await store.loadStations()
        }
        
        // 跳转到充电页面 - 暂时注释掉
          // router.push(`/charging/${selectedChargingStation.value.stationId}`)
          alert(`即将跳转到充电页面: ${selectedChargingStation.value.stationId}`)
      } else {
        throw new Error('充电启动失败')
      }
    } catch (error: any) {
      console.error('充电失败:', error)
      alert(`充电启动失败: ${error.message || '请稍后重试'}`)
      
      // 刷新站点状态
      if (currentLocation.value) {
        // loadStations方法不接受参数
          await store.loadStations()
      } else {
        // 使用loadStations替代refreshStations
          // loadStations方法不接受参数
          await store.loadStations()
      }
    }
    loading.value = false
    showChargingConfirm.value = false
  }

const cancelCharging = () => {
  showChargingConfirm.value = false
  selectedChargingStation.value = null
}

const isStationCharging = (stationId: string): boolean => {
  return chargingStations.value.has(stationId)
}

const getChargeButtonText = (station: Station): string => {
  if (isStationCharging(station.stationId)) return '充电中...'
  if (store.getAvailableCount(station) === 0) return '暂无桩位'
  return '开始充电'
}

const getChargeButtonLabel = (station: Station): string => {
  if (isStationCharging(station.stationId)) return '充电中'
  if (store.getAvailableCount(station) === 0) return '暂无可用桩位'
  return `在${station.stationName}开始充电`
}

// 可访问性相关
const getStationAccessibilityLabel = (station: Station): string => {
  const status = store.getStationStatus(station)
  const availableCount = store.getAvailableCount(station)
  return `状态${getStatusText(status)}, 可用桩位${availableCount}个, 价格每度${station.totalCostPrice}元`
}

// 事件处理
const handleStationClick = (station: Station) => {
  store.setSelectedStation(station)
}

// 性能优化：在站点数量多时启用虚拟滚动
watch(filteredStations, (stations) => {
  enableVirtualScroll.value = stations.length > 50
})

// 初始化
onMounted(() => {
  getCurrentLocation()
})
</script>

<style scoped>
.station-list {
  padding: 16px;
  background: white;
  border-radius: 12px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
  position: relative;
}

.search-box {
  position: relative;
  margin-bottom: 16px;
}

.search-input {
  width: 100%;
  padding: 12px 16px;
  padding-right: 40px;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  font-size: 14px;
  outline: none;
  transition: border-color 0.3s ease;
}

.search-input:focus {
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.clear-search {
  position: absolute;
  right: 12px;
  top: 50%;
  transform: translateY(-50%);
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
  padding: 4px;
}

.clear-search:hover {
  color: #666;
}

/* 位置信息样式 */
.location-info {
  display: flex;
  align-items: center;
  padding: 12px;
  background: #f0f8ff;
  border-radius: 8px;
  margin-bottom: 16px;
  font-size: 14px;
}

.location-icon {
  margin-right: 8px;
}

.location-text {
  flex: 1;
}

.refresh-location {
  background: none;
  border: none;
  cursor: pointer;
  padding: 4px;
  font-size: 16px;
}

/* 路线信息样式 */
.route-info {
  border: 1px solid #e6f7ff;
  border-radius: 8px;
  padding: 16px;
  margin-bottom: 16px;
  background: #f6ffed;
}

.route-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.route-header h4 {
  margin: 0;
  color: #52c41a;
}

.route-header button {
  background: none;
  border: none;
  font-size: 18px;
  cursor: pointer;
  color: #999;
}

.route-details {
  font-size: 14px;
}

.start-navigation {
  margin-top: 8px;
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
}

/* 站点列表容器 */
.stations-container {
  max-height: 600px;
  overflow-y: auto;
}

/* 站点项样式增强 */
.station-item {
  padding: 16px;
  border: 1px solid #f0f0f0;
  border-radius: 8px;
  margin-bottom: 12px;
  cursor: pointer;
  transition: all 0.3s ease;
  position: relative;
}

.station-item:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.1);
}

.station-item.active {
  border-color: #1890ff;
  background: #f0f8ff;
}

.station-item.charging {
  border-color: #52c41a;
  background: #f6ffed;
}

.station-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.station-name {
  margin: 0;
  font-size: 16px;
  font-weight: 600;
  color: #333;
  flex: 1;
}

.distance {
  font-size: 14px;
  color: #666;
  white-space: nowrap;
  margin-left: 8px;
}

.station-info {
  margin-bottom: 12px;
}

.address {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #666;
  line-height: 1.4;
}

.brand, .hours {
  margin: 2px 0;
  font-size: 13px;
  color: #999;
}

.station-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.charger-info {
  display: flex;
  align-items: center;
  font-size: 13px;
}

.charger-info .label {
  color: #999;
}

.charger-info .count {
  color: #333;
  font-weight: 500;
}

.price {
  font-size: 16px;
  font-weight: 600;
  color: #ff4d4f;
}

/* 状态徽章样式增强 */
.status-badge {
  position: absolute;
  top: 12px;
  right: 12px;
  padding: 6px 10px;
  border-radius: 20px;
  font-size: 12px;
  font-weight: 500;
  display: flex;
  align-items: center;
  gap: 4px;
  box-shadow: 0 1px 3px rgba(0,0,0,0.1);
}

.status-badge.free {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-badge.busy {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.status-badge.maintenance {
  background: #fff2f0;
  color: #ff4d4f;
  border: 1px solid #ffccc7;
}

.status-icon {
  font-size: 10px;
}

/* 操作按钮组样式 */
.station-actions {
  display: flex;
  justify-content: flex-end;
  gap: 8px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.route-btn, .charge-btn {
  padding: 8px 16px;
  border: none;
  border-radius: 6px;
  font-size: 14px;
  font-weight: 500;
  cursor: pointer;
  transition: all 0.3s ease;
}

.route-btn {
  background: #1890ff;
  color: white;
}

.route-btn:hover:not(:disabled) {
  background: #40a9ff;
  transform: translateY(-1px);
}

.route-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
  transform: none;
}

.charge-btn {
  background: #52c41a;
  color: white;
}

.charge-btn:hover:not(:disabled) {
  background: #73d13d;
  transform: translateY(-1px);
  box-shadow: 0 2px 6px rgba(82, 196, 26, 0.3);
}

.charge-btn:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
  transform: none;
  box-shadow: none;
}

.charge-btn:active {
  transform: translateY(0);
}

/* 模态对话框样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.charging-modal {
  background: white;
  padding: 24px;
  border-radius: 12px;
  width: 90%;
  max-width: 400px;
  box-shadow: 0 4px 20px rgba(0, 0, 0, 0.15);
}

.charging-modal h3 {
  margin: 0 0 16px 0;
  color: #333;
}

.charging-info {
  margin-bottom: 20px;
}

.charging-info p {
  margin: 8px 0;
  font-size: 14px;
}

.modal-actions {
  display: flex;
  gap: 12px;
  justify-content: flex-end;
}

.btn-cancel, .btn-confirm {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
}

.btn-cancel {
  background: #f5f5f5;
  color: #666;
}

.btn-cancel:hover {
  background: #e8e8e8;
}

.btn-confirm {
  background: #52c41a;
  color: white;
}

.btn-confirm:hover {
  background: #73d13d;
}

/* 加载状态 */
.loading-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(255, 255, 255, 0.8);
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  z-index: 100;
}

.loading-spinner {
  width: 40px;
  height: 40px;
  border: 4px solid #f3f3f3;
  border-top: 4px solid #1890ff;
  border-radius: 50%;
  animation: spin 1s linear infinite;
  margin-bottom: 12px;
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}
</script>